package com.hzgj.bcl.soa.command;

import com.hzgj.bcl.util.lang.StrKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

import static com.hzgj.bcl.soa.command.SoaCommand.secondCommand;

/**
 * Created by warning5 on 2017/3/17.
 */
public class CommandInvoker {

    private static Logger logger = LoggerFactory.getLogger(CommandInvoker.class);

    public static String execute(String command, String scmd, Map<String, String[]> params) {
        String result = "";
        if (StrKit.isBlank(command)) {
            result = badRequestCommand();
        } else {
            SoaCommand soaCommand = CommandsInitializer.getCommand(command);
            if (soaCommand == null) {
                result = badRequestCommand();
            } else {
                SoaCommand.CommandOptions commandOptions = new SoaCommand.CommandOptions();
                commandOptions.params = params;
                if (StrKit.notBlank(scmd)) {
                    commandOptions.params.put(secondCommand, new String[]{scmd});
                }
                try {
                    result = soaCommand.invoke(commandOptions);
                } catch (Exception e) {
                    logger.error("{}", e);
                    result = e.getMessage();
                }
            }
        }
        return result;
    }

    private static String badRequestCommand() {
        return "Bad Format(400) Url pattern: soa/[command]";
    }
}
